/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.rpc.simright;

import cn.hutool.json.JSONObject;
import com.comac.ins.common.core.exception.base.BaseException;
import com.comac.ins.isfd.rpc.simright.bo.SimrightResponseBo;
import com.comac.ins.isfd.rpc.simright.config.SimrightRequestConfig;
import com.comac.ins.isfd.rpc.simright.constants.SimrightConstants;
import com.comac.ins.isfd.rpc.simright.constants.enums.SimrightTaskStatusEnum;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class SimrightRpcUtils {

    @Autowired
    private SimrightRestTemplateUtils simrightRestTemplateUtils;

    @Autowired
    private SimrightRequestConfig simrightRequestConfig;

    /**
     * 调用 /convert_from_local 接口
     */
    public String convertFromLocal(String filePath) {
        // 拼接 URL
        String apiUrl = simrightRequestConfig.getPreUrl() + SimrightConstants.CONVERT_FROM_LOCAL_API;

        // 请求参数（作为 JSON 传参）
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put(SimrightConstants.FILE_PATH_PARAM, filePath);

        // 调用 RestTemplate 封装
        SimrightResponseBo responseBo = simrightRestTemplateUtils.post(apiUrl, paramMap);

        if (responseBo.getData() == null) {
            log.error("调用数巧 convert_from_local 接口返回 data 为空, apiUrl={}, filePath={}", apiUrl, filePath);
            throw new BaseException("调用数巧 convert_from_local 接口失败，返回 data 为空");
        }

        return responseBo.getData();
    }

    /**
     * 调用 /query_convert_task 接口
     */
    public SimrightTaskStatusEnum queryConverTask(String taskId) {
        // 拼接 URL
        String apiUrl = simrightRequestConfig.getPreUrl() + SimrightConstants.QUERY_CONVERT_TASK;

        // 请求参数（作为 JSON 传参）
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put(SimrightConstants.TASK_ID_PARAM, taskId);

        // 调用 RestTemplate 封装
        SimrightResponseBo responseBo = simrightRestTemplateUtils.post(apiUrl, paramMap);

        String data = responseBo.getData();

        String taskStatus = null;
        if (data != null) {
            JSONObject json = new JSONObject(data);
            taskStatus = json.getStr("task_status");
        }

        if (StringUtil.isBlank(taskStatus)) {
            log.error("调用数巧 {} 接口失败，返回 data 为空, task_id:{}",SimrightConstants.QUERY_CONVERT_TASK, taskId );
            throw new BaseException("调用数巧 {} 接口失败，返回 data 为空",SimrightConstants.QUERY_CONVERT_TASK );
        }

        return SimrightTaskStatusEnum.forValue(taskStatus);
    }

}
